/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
 var rightSideView = function(root) {
    let res=[];
    if(!root){
        return res;
    }
    let arr=[root];
    let head=0,end=1;
    while(head!=end){
        let length=end-head;
        let level=[];
        for(let i=0;i<length;i++){
            if(arr[head].left){
                arr.push(arr[head].left);
            }
            if(arr[head].right){
                arr.push(arr[head].right);
            }
            level.push(arr[head].val);
            head++;
        }
        res.push(level[length-1]);
        end=arr.length;
    }
    return res;
};